<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>移动端游戏</title>
    <script src="js/phaser.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            background-color: #000;
            overflow: hidden;
            touch-action: none;
            -webkit-touch-callout: none;
            -webkit-user-select: none;
            -khtml-user-select: none;
            -moz-user-select: none;
            -ms-user-select: none;
            user-select: none;
            font-family: 'Arial', sans-serif;
        }
        
        #gameContainer {
            width: 100vw;
            height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            position: relative;
        }
        
        #startScreen {
            position: absolute;
            width: 100%;
            height: 100%;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            background: linear-gradient(135deg, #1a2a6c, #b21f1f, #fdbb2d);
            z-index: 10;
            color: white;
            text-align: center;
            padding: 20px;
        }
        
        .title {
            font-size: 2.5rem;
            margin-bottom: 20px;
            text-shadow: 2px 2px 4px rgba(0,0,0,0.5);
        }
        
        .instructions {
            font-size: 1.2rem;
            margin-bottom: 30px;
            max-width: 80%;
            line-height: 1.5;
        }
        
        #startButton {
            padding: 15px 40px;
            font-size: 1.5rem;
            background: linear-gradient(to bottom, #4CAF50, #388E3C);
            color: white;
            border: none;
            border-radius: 50px;
            cursor: pointer;
            margin-top: 20px;
            box-shadow: 0 6px 0 #2E7D32, 0 8px 10px rgba(0,0,0,0.3);
            transition: all 0.2s;
            font-weight: bold;
            letter-spacing: 1px;
        }
        
        #startButton:active {
            transform: translateY(4px);
            box-shadow: 0 2px 0 #2E7D32, 0 4px 6px rgba(0,0,0,0.3);
        }
        
        #game {
            width: 100%;
            height: 100%;
        }
        
        .control-hint {
            position: absolute;
            bottom: 20px;
            width: 100%;
            display: flex;
            justify-content: space-between;
            padding: 0 20px;
            color: rgba(255,255,255,0.7);
            font-size: 0.9rem;
            pointer-events: none;
            z-index: 5;
        }
        
        .hint-left, .hint-right {
            background: rgba(0,0,0,0.5);
            padding: 8px 15px;
            border-radius: 20px;
        }
    </style>
</head>
<body>
    <div id="gameContainer">
        <div id="startScreen">
            <h1 class="title">移动端游戏</h1>
            <p class="instructions">左下区域控制移动，右下区域控制攻击<br>支持多点触控操作</p>
            <button id="startButton">进入游戏</button>
        </div>
        <div id="game"></div>
        <!-- <div class="control-hint">
            <div class="hint-left">移动控制区</div>
            <div class="hint-right">攻击控制区</div>
        </div> -->
    </div>

    <script>
        // 检查是否在全屏状态
        function isFullscreen() {
            return !!(document.fullscreenElement || 
                     document.webkitFullscreenElement || 
                     document.mozFullScreenElement || 
                     document.msFullscreenElement);
        }
        
        // 页面加载时检查
        window.addEventListener('load', function() {
            if (isFullscreen()) {
                if (document.exitFullscreen) {
                    document.exitFullscreen();
                }
            }
        });

        // 游戏变量
        let player;
        let moveDirection = { x: 0, y: 0 };
        let moveSpeed = 200;
        
        let movePointerId = null;
        let attackPointerId = null;
        let gameScene;

        
        // 初始化游戏
        let game;
        let logtext;
        

        // 重构代码
        // 移动,攻击按钮
        let mb1,mb2,at1, at2;

        // 攻击效果
        let attackCooldown = 0;
        let attackReady = false;
        let attack = { x: 0, y: 0 };
        let isAttacking = false;
        let attackDirection = 0;

        let attackStartTime = 0; // 攻击键按下的初始时间（毫秒）
        const MAX_CHARGE_TIME = 500; // 最大蓄力时间（2000毫秒=2秒）
        const INITIAL_RADIUS = 80;
        const FINAL_RADIUS = 500;
        const INITIAL_ANGLE = Math.PI / 6; // 60度（弧度）
        const FINAL_ANGLE = Math.PI / 720; // 1度（弧度）


        function preload() {
            // 预加载资源
            this.load.image('bullet', 'assets/pic/bullet.png');
            this.load.image('soldier', 'assets/pic/soldier.png');
            this.load.image('bandit', 'assets/pic/bandit.png');


            this.load.audio('loadThePistol', 'assets/sound/loadThePistol.mp3');
            this.load.audio('pistolFiring', 'assets/sound/pistolFiring.mp3');
        }

        function create() {

             this.pistolFiring = this.sound.add('pistolFiring', {
                volume: 0.5, // 音量（0-1）
                rate: 1,     // 播放速度（1 正常，0.5 慢放，2 快放）
                loop: false  // 是否循环（音效通常不循环）
            });
            this.loadThePistol = this.sound.add('loadThePistol', {
                volume: 0.5, // 音量（0-1）
                rate: 2,     // 播放速度（1 正常，0.5 慢放，2 快放）
                loop: false  // 是否循环（音效通常不循环）
            });



            gameScene = this;
            this.physics.world.enable(this);
            this.enemies = this.physics.add.group();

            // 创建玩家角色
            const gameWidth = this.scale.width;
            const gameHeight = this.scale.height;

            player = this.physics.add.sprite(gameWidth / 2, gameHeight / 2,'soldier');
            player.body.collideWorldBounds = true; 

            // 创建攻击区域指示器
            attackZone = this.add.graphics();
            
            // 设置输入
            setupInput(this);
            
            // 隐藏开始界面
            document.getElementById('startScreen').style.display = 'none';


            logtext = this.add.text(
                10, // 文本 x （背景框内边距）
                20, // 文本 y （背景框内边距）
                '日志内容', // 初始为空
                {
                    fontSize: '14px',
                    fill: '#ffffff', // 白色文字
                    fontFamily: ' monospace',
                    wordWrap: { width: 800} // 自动换行
                }
                ).setOrigin(0, 1);

            genEnemies(this,5);
            this.time.addEvent({
                delay: 3000, // 间隔时间（毫秒）
                loop: true, // 循环执行
                callback: () => {
                    const count = Phaser.Math.Between(1, 2); // 随机生成1-2个
                    genEnemies(this,count);
                }
            });
        }

        function setupInput(scene) {
            // 移动摇杆输入 - 使用指针ID跟踪多点触控
            scene.input.on('pointerdown', function(pointer) {
                const screenWidth = scene.scale.width;
                const screenHeight = scene.scale.height;
                const leftRegion = screenWidth * 0.5;
                const bottomRegion = screenHeight * 0.5;
                
                if (pointer.x < leftRegion && pointer.y > bottomRegion && movePointerId === null) {
                    // 左下区域 - 移动
                    movePointerId = pointer.id;
                    
                    if(!mb1){
                        mb1 = scene.add.circle(pointer.x, pointer.y, 30, 0xc0300b, 0.3);
                        mb1.setStrokeStyle(3, 0xa93226);
                        mb1.setScrollFactor(0);
                    }else{
                        mb1.x = pointer.x;
                        mb1.y = pointer.y;
                        mb1.alpha=0.5;
                    }

                } else if (pointer.x > screenWidth - leftRegion && pointer.y > bottomRegion && attackPointerId === null) {
                    // 右下区域 - 攻击
                    attackPointerId = pointer.id;
                    attackStartTime = Date.now();
                    scene.loadThePistol.play(); 
                    if(!at1){
                        at1 = scene.add.circle(pointer.x, pointer.y, 30, 0xc030ff, 0.3);
                        at1.setStrokeStyle(3, 0xa93226);
                        at1.setScrollFactor(0);
                    }else{
                        at1.x = pointer.x;
                        at1.y = pointer.y;
                        at1.alpha=0.3;
                    }

                    isAttacking = true;
                    attackReady = true;
                }
            });
            
            scene.input.on('pointermove', function(pointer) {
                if (pointer.id === movePointerId) {
                    
                    if(!mb2){
                        mb2 = scene.add.circle(pointer.x, pointer.y, 30, 0xc2292b, 0.3);
                        mb2.setStrokeStyle(3, 0xa93226);
                        mb2.setScrollFactor(0);
                    }
                    mb2.alpha=0.5;

                    // 移动摇杆
                    const dx = pointer.x - mb1.x;
                    const dy = pointer.y - mb1.y;
                    const distance = Math.sqrt(dx * dx + dy * dy);
                    const maxDistance = 60;
                    
                    if (distance > maxDistance) {
                        moveDirection.x = dx / distance;
                        moveDirection.y = dy / distance;
                        mb2.x = mb1.x + dx/distance*maxDistance;
                        mb2.y = mb1.y + dy/distance*maxDistance;
                    } else {
                        moveDirection.x = dx / maxDistance;
                        moveDirection.y = dy / maxDistance;
                        mb2.x = pointer.x;
                        mb2.y = pointer.y;
                    }
                    
                } else if (pointer.id === attackPointerId && isAttacking) {
                    // 攻击摇杆
                    const dx = pointer.x - at1.x;
                    const dy = pointer.y - at1.y;
                    const distance = Math.sqrt(dx * dx + dy * dy);
                    const maxDistance = 60;


                    if(!at2){
                        at2 = scene.add.circle(pointer.x, pointer.y, 30, 0xc030ff, 0.3);
                        at2.setStrokeStyle(3, 0xa93226);
                        at2.setScrollFactor(0);
                    }
                    at2.alpha=0.3;
                    
                    if (distance > maxDistance) {
                        at2.x = at1.x + dx/distance*maxDistance;
                        at2.y = at1.y + dy/distance*maxDistance;
                    } else {
                        at2.x = pointer.x;
                        at2.y = pointer.y;
                    }
                    attackDirection = Math.atan2(dy, dx);
                    
                    // 绘制攻击方向扇形
                    const { radius, angle } = getChargeParams(); // 获取当前参数
                    attackZone.clear();
                    attackZone.fillStyle(0xe74c3c, 0.4);
                    attackZone.slice(
                        player.x, 
                        player.y, 
                        radius, // 动态半径
                        attackDirection - angle, // 动态左角度
                        attackDirection + angle  // 动态右角度
                    );
                    attackZone.fillPath();
                    attackZone.lineStyle(2, 0xc0392b, 0.8);
                    attackZone.strokePath();

                }
            });
            
            scene.input.on('pointerup', function(pointer) {
                if (pointer.id === movePointerId) {
                    mb1.alpha=0;
                    mb2.alpha=0;
                    // 移动摇杆释放 - 回到初始位置
                    movePointerId = null;
                    moveDirection.x = 0;
                    moveDirection.y = 0;
                } else if (pointer.id === attackPointerId) {
                    // 攻击摇杆释放 - 回到初始位置
                    attackPointerId = null;
                    at1.alpha=0;
                    at2.alpha=0;
                    isAttacking = false;

                    if (attackReady && attackCooldown <= 0) {
                        attack.x = player.x + (at2.x -at1.x);
                        attack.y = player.y + (at2.y -at1.y);
                        performAttack(scene);

                        attackCooldown = 30;
                        attackReady = false;
                    }
                    
                    attackZone.clear();
                }
            });
        }

        function performAttack(scene) {
            scene.pistolFiring.play(); 
            const bullet = scene.physics.add.sprite(player.x, player.y, 'bullet');
            // 设置子弹物理属性
            bullet.setScale(0.3)
            bullet.setSize(10, 10); // 碰撞体大小（根据图片调整）
            bullet.setVelocity(0); // 初始速度为 0

            // 计算从玩家到目标点的方向向量
            const speed = 1000; // 子弹速度
            const angle = Phaser.Math.Angle.Between(
                player.x, player.y,
                attack.x, attack.y
            );

            // 沿计算的角度设置子弹速度
            scene.physics.velocityFromAngle(
                Phaser.Math.RadToDeg(angle), // 角度转为度数
                speed,
                bullet.body.velocity
            );
            bullet.setRotation(angle+Phaser.Math.DegToRad(45)); 

            scene.time.delayedCall(2000, () => { // 2秒后检查
                if (bullet.active) bullet.destroy();
            });

            scene.physics.add.overlap(
                bullet,               // 碰撞体1：子弹
                scene.enemies,        // 碰撞体2：敌人组（第1段初始化的enemies）
                (hitBullet, hitEnemy) => { // 碰撞回调：hitBullet=被触发的子弹，hitEnemy=被命中的敌人
                    // hitBullet.destroy();  // 销毁子弹
                    if (hitEnemy.moveTimer) {
                        hitEnemy.moveTimer.remove(false); // false 表示立即停止，不触发最后一次回调
                        hitEnemy.moveTimer = null; // 清除引用
                    }

                    // 关键2：销毁敌人前，手动清除物理体引用（额外保险）
                    if (hitEnemy.body) {
                        hitEnemy.body.destroy(); // 销毁物理体
                    }

                    // 最后销毁敌人
                    hitEnemy.destroy();
                }
            );
        }

        function getChargeParams() {
            if (!isAttacking) {
                // 未攻击时返回初始值
                return {
                    radius: INITIAL_RADIUS,
                    angle: INITIAL_ANGLE
                };
            }

            // 计算按下时长（毫秒）
            const currentTime = Date.now();
            const chargeTime = currentTime - attackStartTime;
            // 限制最大时长为2秒
            const t = Math.min(chargeTime / MAX_CHARGE_TIME, 1); // t范围：0~1

            // 插值计算半径（从80到400）
            const radius = Phaser.Math.Linear(INITIAL_RADIUS, FINAL_RADIUS, t);
            // 插值计算角度（从60度到1度，取半角，因为扇形是左右对称的）
            const angle = Phaser.Math.Linear(INITIAL_ANGLE, FINAL_ANGLE, t);

            return { radius, angle };
        }

        function genEnemies(scene,count){
            for(let i=0;i<count;i++){
                const gameWidth = scene.scale.width;
                const gameHeight = scene.scale.height;
                const x = Phaser.Math.Between(100, gameWidth - 100);
                const y = Phaser.Math.Between(20, gameHeight - 20);
                
                // 创建敌人时指定物理体配置（确保启用）
                const enemy = scene.enemies.create(x, y, 'bandit', {
                    physicsBodyType: Phaser.Physics.Arcade.DYNAMIC_BODY // 显式指定物理体类型
                });
                
                // 再设置碰撞体大小（确保在物理体初始化后）
                enemy.body.setSize(50, 50);
                enemy.body.collideWorldBounds = true; 

                setEnemyRandomMovement(scene, enemy);
            }
        }

        function setEnemyRandomMovement(scene, enemy) {
            // 随机运动参数（可调整）
            const minSpeed = 50;    // 最小移动速度（像素/秒）
            const maxSpeed = 150;   // 最大移动速度
            const minChangeTime = 1000; // 最小方向切换间隔（毫秒）
            const maxChangeTime = 3000; // 最大方向切换间隔

            // 初始随机方向和速度
            function setRandomVelocity() {
                const randomAngle = Phaser.Math.Between(0, 360); // 0-360度随机方向
                const randomSpeed = Phaser.Math.Between(minSpeed, maxSpeed);
                // 根据角度和速度设置x/y轴速度
                scene.physics.velocityFromAngle(randomAngle, randomSpeed, enemy.body.velocity);
            }

            // 初始设置一次速度
            setRandomVelocity();

            // 定时切换方向（每1-3秒随机一次）
            enemy.moveTimer = scene.time.addEvent({
                delay: Phaser.Math.Between(minChangeTime, maxChangeTime),
                loop: true,
                callback: () => {
                    setRandomVelocity(); // 重新生成随机方向和速度
                }
            });

            // 边界检测：敌人碰到屏幕边缘时反弹（避免移出屏幕）
            enemy.body.collideWorldBounds = true; // 启用世界边界碰撞
            enemy.body.bounce.set(1); // 碰撞后完全反弹（0-1之间，1=无能量损失）
        }

        function update() {
            // 更新玩家移动
            if (player && player.body) {
                player.body.setVelocity(
                    moveDirection.x * moveSpeed,
                    moveDirection.y * moveSpeed
                );
            }
            
            // 更新攻击冷却
            if (attackCooldown > 0) {
                attackCooldown--;
            }
            
            // 更新攻击指示器位置
            if (isAttacking && attackReady && player) {
                const { radius, angle } = getChargeParams(); // 获取当前参数
                attackZone.clear();
                attackZone.fillStyle(0xe74c3c, 0.4);
                attackZone.slice(
                    player.x, 
                    player.y, 
                    radius, // 动态半径
                    attackDirection - angle, // 动态左角度
                    attackDirection + angle  // 动态右角度
                );
                attackZone.fillPath();
                attackZone.lineStyle(2, 0xc0392b, 0.8);
                attackZone.strokePath();
            }
        }

        // 开始游戏按钮事件
        document.getElementById('startButton').addEventListener('click', function() {
            // 进入全屏
            if (document.documentElement.requestFullscreen) {
                document.documentElement.requestFullscreen();
            }
            
            // 使用当前窗口尺寸创建游戏配置
            const config = {
                type: Phaser.AUTO,
                width: window.innerWidth,
                height: window.innerHeight,
                parent: 'game',
                backgroundColor: '#2c3e50',
                scene: {
                    preload: preload,
                    create: create,
                    update: update
                },
                scale: {
                    mode: Phaser.Scale.RESIZE,
                    autoCenter: Phaser.Scale.CENTER_BOTH
                },
                physics: {
                    default: 'arcade',
                    arcade: {
                        gravity: { y: 0 },
                        debug: false
                    }
                },
                input: {
                    activePointers: 3
                }
            };            
            
            // 等待全屏后启动游戏
            setTimeout(() => {
                game = new Phaser.Game(config);
                document.getElementById('startScreen').style.display = 'none';
            }, 300);
        });

        // 处理窗口大小变化
        window.addEventListener('resize', function() {
            if (game) {
                game.scale.refresh();
            }
        });
    </script>
</body>
</html>